from playwright.sync_api import sync_playwright, TimeoutError as PlaywrightTimeoutError

def main():
    """Main function to call the login_facebook function with example arguments."""
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False, slow_mo=100)
        page = browser.new_page()

        page.goto("https://www.facebook.com/AFKJourneyOfficial/posts/pfbid02jccqweFFPiqF5ARJusbx2PHQ2Fy1uEzDWxytfw4xZSyZ6fFzpkv6n3Eyt3ubgkCvl?__cft__[0]=AZVgSGoqoo7pYYYGlvRDlT4_KgLags6R6lG8cezRDqM_Q7uiSrbyH-Y0smNUqvhCuUIj3RaSOv8P6nVi3msFlpm9rkinvN_GGxpC94uilaVn86zTf4hvajEdzToLG1MNGFxKLArIE2Ibe_yxxIIFheiR2ZS8bMGdjau0Pu9i_SVLrIXVf9Q3psJ9PeqRTM4K4eQ&__tn__=%2CO%2CP-R")
        content = get_post_content(page)
        comments_count = get_comments_count(page)
        
        if comments_count > 0:
            get_comments(page)
        else:
            print("没有评论")

        browser.close()

def get_post_content(page):
    """Extracts the full post content."""
    try:
        content_elements = page.locator('//*[contains(@id, ":")]//div[@dir="auto"]').all_text_contents()
        
        # 合并所有文本内容
        full_post_content = " ".join(content_elements)
        print("帖子内容:", full_post_content.strip())
        
        # 返回提取的内容以便其他函数使用
        return full_post_content.strip()
    except PlaywrightTimeoutError:
        print("Error getting full post content: Timeout")       

def get_comments_count(page):
    """Extracts the comments count."""
    try:
        # 使用更精确的选择器，定位到包含"条评论"文本的元素
        comments_count_text = page.get_by_role("button", name="条评论").text_content()
        print("评论数文本:", comments_count_text)
        # 处理评论数量文本，提取数字部分
        comments_count = 0
        try:
            if "条评论" in comments_count_text:
                # 从文本中提取数字部分（例如从"37条评论"中提取"37"）
                comments_count = int(comments_count_text.replace("条评论", "").strip())
            elif "评论" in comments_count_text:
                # 处理可能的其他格式
                comments_count = int(comments_count_text.split("评论")[0].strip())
            
            print(f"评论数量（数字）: {comments_count}")
            return comments_count
        except ValueError:
            print("无法将评论数量转换为整数，使用默认值0")
            return 0
    except PlaywrightTimeoutError:
        print("Error getting comments count: Timeout")
    except Exception as e:
        print(f"获取评论数量时出错: {e}")
        return 0

def get_comments(page):
    """Extracts the comments."""
    comments = []
    try:
        # 首先点击评论排序菜单并选择"由新到旧"
        load_all_comments(page)
        
        # 等待评论加载
        page.wait_for_timeout(2000)  # 等待2秒让评论加载
        
        comment_containers = page.locator('div.x1lliihq.xjkvuk6.x1iorvi4')
        count = comment_containers.count()
        print(f"找到 {count} 个评论容器")
        
        for i in range(count):
            try:
                # 获取当前评论容器
                container = comment_containers.nth(i)
                
                # 查找所有 dir="auto" 的 div 元素
                text_divs = container.locator('div[dir="auto"]')
                text_divs_count = text_divs.count()
                
                if text_divs_count == 0:
                    continue
                
                # 如果只有一个文本元素，直接获取内容
                if text_divs_count == 1:
                    comment_text = text_divs.first.text_content().strip()
                    comments.append(comment_text)
                else:
                    # 如果有多个文本元素，合并它们的内容
                    combined_text = []
                    for j in range(text_divs_count):
                        div_text = text_divs.nth(j).text_content().strip()
                        if div_text:  # 只添加非空文本
                            combined_text.append(div_text)
                    
                    if combined_text:
                        comment_text = " | ".join(combined_text)
                        comments.append(comment_text)
                
                print(f"评论 {i+1}: {comments[-1] if comments else '(空)'}")
                
            except Exception as comment_error:
                print(f"获取第 {i+1} 个评论时出错: {comment_error}")
                continue
        
        print(f"成功获取 {len(comments)} 条评论")
        return comments
    except PlaywrightTimeoutError:
        print("Error getting comments: Timeout")
    except Exception as e:
        print(f"获取评论时出错: {e}")
    
    return comments

def load_all_comments(page):
    """点击评论排序菜单并选择'由新到旧'选项"""
    try:
        # 点击带有aria-haspopup="menu"属性的div元素
        print("尝试点击评论排序菜单...")
        menu_button = page.locator('div.x6s0dn4.x78zum5.xdj266r.x11i5rnm.xat24cr.x1mh8g0r.xe0p6wg > div > span').first
        menu_button.click()
        
        # 等待菜单出现
        page.wait_for_timeout(1000)  # 等待1秒让菜单显示
        
        # 点击"由新到旧"选项
        print("尝试选择'由新到旧'选项...")
        all_comments_option = page.get_by_text("由新到旧", exact=True)
        if all_comments_option.count() > 0:
            all_comments_option.click()
            print("成功选择'由新到旧'选项")
                
        # 等待菜单关闭和页面更新
        page.wait_for_timeout(1000)

        # 向下滚动，直到指定元素的子元素为空
        print("开始滚动加载更多评论...")
        max_scrolls = 20  # 设置最大滚动次数，防止无限循环
        scroll_count = 0
        
        while scroll_count < max_scrolls:
            # 检查目标元素的子元素是否为空
            target_element = page.locator('div.xdj266r.x11i5rnm.xat24cr.x1mh8g0r.xexx8yu.x4uap5.x18d9i69.xkhd6sd.x78zum5.x13a6bvl')
            if target_element.count() > 0:
                children_count = target_element.locator('> *').count()
                if children_count == 0:
                    print("已加载所有评论，停止滚动")
                    break
            
            # 向下滚动
            # 在指定的评论容器中滚动而不是整个页面
            comments_container = page.locator('div.xb57i2i.x1q594ok.x5lxg6s.x78zum5.xdt5ytf.x6ikm8r.x1ja2u2z.x1pq812k.x1rohswg.xfk6m8.x1yqm8si.xjx87ck.xx8ngbg.xwo3gff.x1n2onr6.x1oyok0e.x1odjw0f.x1iyjqo2.xy5w88m').first
            comments_container.evaluate("e => e.scrollTop += 500")
            page.wait_for_timeout(1000)  # 等待内容加载
            scroll_count += 1
            
        if scroll_count >= max_scrolls:
            print(f"已达到最大滚动次数({max_scrolls})，停止滚动")
        
    except PlaywrightTimeoutError:
        print("选择评论排序选项时超时")
    except Exception as e:
        print(f"选择评论排序选项时出错: {e}")

if __name__ == "__main__":
    main()
